﻿using System.Web.Mvc;
using System.Web.Routing;
using Kiwi.Container.Application;
using Kiwi.Container.DependencyInjection;

namespace Kiwi.Container.Web.Mvc
{
    public class DependencyInjectingControllerFactory : IControllerFactory
    {
        private readonly IControllerFactory _controllerFactory;
        private readonly IEnumerateDependentProperties _dependentProperties;

        public DependencyInjectingControllerFactory(IControllerFactory controllerFactory, IEnumerateDependentProperties dependentProperties)
        {
            _controllerFactory = controllerFactory;
            _dependentProperties = dependentProperties;
        }

        #region IControllerFactory Members

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            var controller = _controllerFactory.CreateController(requestContext, controllerName);
            if (controller != null)
            {
                ContainerManager.Current.Inject(controller, _dependentProperties);
            }
            return controller;
        }

        public void ReleaseController(IController controller)
        {
            _controllerFactory.ReleaseController(controller);
        }

        #endregion
    }
}